package com.zzx.dynamicDataSoure;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;

/**
 * 
 * @ClassName: DataSourceAspect 
 * @Description: 切换数据库
 * @author zzx
 *
 * @date 2020年6月29日
 */
public class DataSourceAspect implements MethodBeforeAdvice, AfterReturningAdvice {
	
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		DynamicDataSourceHolder.putDataSource("master");		
	}

	public void before(Method method, Object[] args, Object target) throws Throwable {
		try {
			if (method != null && method.isAnnotationPresent(DataSource.class)) {
				DataSource data = method.getAnnotation(DataSource.class);
				DynamicDataSourceHolder.putDataSource(data.value());
			} else if (method != null) {
				DynamicDataSourceHolder.putDataSource("master");
			}
		} catch (Exception e) {
			DynamicDataSourceHolder.putDataSource("master");			
		}
	}

}
